package org.example.blog.services.impl;

import org.example.blog.daos.FavoriteDAO;
import org.example.blog.entities.Favorite;
import org.example.blog.entities.Post;
import org.example.blog.entities.User;
import org.example.blog.services.FavoriteService;
import org.example.blog.services.PostService;
import org.zoomdev.zoom.common.utils.Page;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

public class FavoriteServiceImpl implements FavoriteService {
    // 伪代码，假设注入了FavoriteDAO和PostDAO
    private FavoriteDAO favoriteDAO;
    private PostService postDAO;

    @Override
    public Favorite addFavorite(Long userId, Long postId) {
        // 检查是否已经收藏，避免重复收藏
        if (favoriteDAO.existsByUserIdAndPostId(userId, postId)) {
            throw new RuntimeException("已经收藏过该文章");
        }

        Favorite favorite = new Favorite();
        favorite.setUser(new User()); // 设置用户ID
        favorite.setPost(new Post()); // 设置文章ID
        favorite.setCreatedAt(LocalDateTime.now());

        // 保存收藏记录
        favoriteDAO.save(favorite);
        return favorite;
    }

    @Override
    public void removeFavorite(Long favoriteId) {
        // 直接删除收藏记录
        favoriteDAO.deleteById(favoriteId);
    }

    @Override
    public boolean isFavorite(Long userId, Long postId) {
        return favoriteDAO.existsByUserIdAndPostId(userId, postId);
    }

    @Override
    public Page<Post> getUserFavorites(Long userId, int page, int size) {
        // 先获取收藏记录的分页
        Page<Favorite> favorites = favoriteDAO.findByUserId(userId, page, size);

        // 从收藏记录中提取文章ID列表
        List<Long> postIds = favorites.getList().stream()
                .map(favorite -> favorite.getPost().getId())
                .collect(Collectors.toList());

        // 根据文章ID列表查询文章
        List<Post> posts = postDAO.findByIds(postIds);

        // 返回文章的分页，注意总数为收藏记录的总数
        return new Page<>(posts, page, size, favorites.getTotalRows());
    }
}
